package com.picket.service;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Service;

import com.picket.dao.IPoolDao;
import com.picket.dao.IUserPoolDao;
import com.picket.dao.IUserPredictionDao;
import com.picket.domain.Pool;
import com.picket.domain.UserPool;
import com.picket.domain.UserPrediction;

@Service
public class UserPoolService implements  IUserPoolService{
	 
	 private IUserPoolDao userPoolDao;
	  
	 @Required
	 public void setUserPoolDao(
	      final IUserPoolDao userPoolDao) {
	    this.userPoolDao = userPoolDao;
	 }

	private IUserPredictionDao userPredictionDao;

	@Required
	public void setUserPredictionDao(final IUserPredictionDao userPredictionDao) {
		this.userPredictionDao = userPredictionDao;
	}
	
	private IPoolDao poolDao;
	
	@Required
	public void setPoolDao(final IPoolDao eventDao) {
		this.poolDao = eventDao;
	}
	
	 @Override
	 public UserPool create(final UserPool userPool) {
		 return userPoolDao.create(userPool);
	 }
	 
	 @Override
	 public Collection<UserPool> getAllUserPools() {
	  return userPoolDao.getAllUserPools();
	 }

	 @Override
	 public Collection<UserPool> getAllUserPoolsForEvent(long id) {
	  return userPoolDao.getAllUserPoolsForEvent(id);
	 }
	 
	@Override
	public UserPool getUserPool(long id) {
		return userPoolDao.getUserPool(id);
	}

	@Override
	public Collection<UserPool> getAllUserPoolInfoForPool(
			long poolId) {
		return userPoolDao.getAllUserPoolsForPool(poolId);
	}	
	
	public Collection<UserPool> findByEmail(String email){
		return userPoolDao.findByEmail(email);
	}

	@Override
	public void updatePoints(long eventId) {
		Collection<UserPool> allUserPoolsForEvents = getAllUserPoolsForEvent(eventId);
		for (UserPool userPool : allUserPoolsForEvents) {
			Collection<UserPrediction> userPredsForUserPool = userPredictionDao
					.getAllUserPredictionsForUserPool(userPool.getId());

			Integer totalPoints = 0;
			Integer totalCorrect = 0;
			for (UserPrediction pred : userPredsForUserPool) {
				Integer predPoints = (pred.getPredictionPoints()==null?0:pred.getPredictionPoints());
				totalPoints = totalPoints + predPoints;
				if (predPoints > 0) {
					totalCorrect = totalCorrect + 1;
				}

			}
			userPoolDao.updatePoints(userPool.getId(), totalPoints,
					totalCorrect);

		}

	}
	@Override
	public Collection<UserPool> findByEmailAndPoolId(String email,long poolId){
		return userPoolDao.findByEmailAndPoolId(email,poolId);
	}
	
	@Override
	public void updateStandings(long eventId) {
		Collection<Pool> pools = poolDao.getAllPoolsForEvent(eventId);
		//TODO complete
	}
	
	
	public UserPool findByPoolId(long poolId){
		return userPoolDao.findByPoolId(poolId);
	}	
}
